// 人员选择
App.directive('edUserSelect', ['$rootScope', '$compile', 'Page', function ($rootScope, $compile, Page) {
    return {

        restrict: 'A',
        scope: {
            model : '@ngModel',
            userId: '=edUser',
            deptId: '=edDept'
        },
        require: 'ngModel',
        templateUrl: 'views/directive/userSelect.html',

        controller: ['$scope', '$element', function ($scope, $element) {

            $scope.users = [], $scope.userSelected = [];
            $scope.treeId = Metronic.getUniqueID();
            $scope.showType = 'org';// 默认安装组织机构分组

            // 同步选中
            $scope.treeSynCheck = function(source, dest) {
                var checkedNodes = source.getCheckedNodes(true);

                // 先取消选中
                dest.setting.view.expandSpeed = "";
                dest.checkAllNodes(false);
                dest.expandAll(false);
                dest.setting.view.expandSpeed = "fast";

                $(checkedNodes).each(function (index, item) {
                    if (item.type == 'user') {// 人员
                        $(dest.getNodesByParam('id', item.id, null)).each(function(index2, node) {
                            if (node.deptid == item.deptid && node.posid == item.posid) {// 部门和岗位都相同的
                                dest.checkNode(node, true, true);
                            }
                        });
                    }
                });
                // 展开所有选中节点
                checkedNodes = dest.getCheckedNodes(true), checkedLen = checkedNodes.length;
                if (checkedLen > 0) {
                    for (var i = 0; i < checkedLen; i++) {
                        dest.expandNode(checkedNodes[i], true);
                    }
                }
            }

            // 删除选择
            $scope.unselect = function(user) {
                $($scope.userSelected).each(function(index, item) {
                    if (item.id == user.id) {
                        $scope.userSelected.splice(index, 1);// $scope.userSelected里面没有重复的，点击这里全部删除
                        return false;
                    }
                });
                var nodes = $scope.orgTree.getNodesByParam('id', user.id, null);
                $(nodes).each(function(index, node) {
                    $scope.orgTree.checkNode(node, false, true);
                });

                nodes = $scope.posTree.getNodesByParam('id', user.id, null);
                $(nodes).each(function(index, node) {
                    $scope.posTree.checkNode(node, false, true);
                });
            }

            // 确定选择
            $scope.select = function() {
                $scope._ok = true;
                $scope.modal.hide();
            }

            // 取消选择
            $scope.onHidden = function() {
                if ($scope._ok) {// 说明是通过点击确定关闭的
                    $scope.users = angular.copy($scope.userSelected);
                    $scope.updateValue();
                    $scope._ok = false;
                } else {
                    // 还原最近选择的
                    $scope.userSelected = angular.copy($scope.users);
                    $scope.updateTree($scope.orgTree);
                    if ($scope.multiple) {
                        $scope.updateTree($scope.posTree);
                    }
                }
            }

            $scope.search = function() {
                Ztree.search($scope.orgTree, 'name', $scope.userName, function(node) {
                    return node.type == 'user';
                });
            }
        }],

        link: function (scope, elem, attrs, ngModelController) {
            var input = elem.find('input[type="text"]:eq(0)');
            // 如果设置了人员和部门，不支持按照岗位树显示
            if (attrs.edUser || attrs.edDept) {
                $(elem).find('.radio-inline:eq(1)').hide();
            }
            scope.multiple = attrs.edMultiple == 'true';

            var setting = {
                check: {
                    enable: scope.multiple
                },
                view: {
                    selectedMulti: false,
                    fontCss: function(treeId, treeNode) {
                        return (treeNode.highlight == '1') ? {color:"#A60000", "font-weight":"bold"} : {color:"#333", "font-weight":"normal"};
                    }
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    onClick: function(event, treeId, treeNode, clickFlag) {// 单选
                        if (!scope.multiple) {
                            if (treeNode.isParent) {
                                scope.orgTree.expandNode(treeNode);
                            } else {
                                if (treeNode.type == 'user') {// 人员
                                    scope.$apply(function() {
                                        scope.userSelected = [];
                                        scope.userSelected.push(treeNode);
                                    });
                                }
                            }
                        }
                    },
                    onDblClick: function(event, treeId, treeNode) {
                        if (!scope.multiple && treeNode.type == 'user') {// 单选时双击确定
                            scope.select()
                        }
                    },
                    onCheck : function (event, treeId, treeNode) {// 多选
                        var source;
                        if (treeId == 'orgTree' + scope.treeId) {
                            source = scope.orgTree;
                            scope.treeSynCheck(scope.orgTree, scope.posTree);
                        } else {
                            source = scope.posTree;
                            scope.treeSynCheck(scope.posTree, scope.orgTree);
                        }

                        scope.$apply(function () {
                            $(getChildren(treeNode)).each(function (index, relative) {
                                if (relative.type == 'user') {// 人员
                                    if (relative.checked) {// 选中
                                        if (!contains(relative)) {// 去重复
                                            scope.userSelected.push(relative);
                                        }
                                    } else {// 取消选中
                                        $(scope.userSelected).each(function (index1, user) {
                                            if (relative.id == user.id) {
                                                // 如果岗位存在选中，则不能取消
                                                var have = false;
                                                $(source.getNodesByParam('id', relative.id, null)).each(function(index2, node) {
                                                    if (!(node.deptid == relative.deptid && node.posid == relative.posid) && node.checked) {// 部门和岗位都相同的
                                                        have = true;
                                                    }
                                                });
                                                if (!have) {// 不存在其他部门、岗位下选中的
                                                    scope.userSelected.splice(index1, 1);
                                                }
                                                return false;
                                            }
                                        });
                                    }
                                }
                            });
                        });
                    }
                }
            }

            var key = '_userTree:' + (scope.deptId || '') + ":" + (scope.userId || '');
            if ($rootScope[key]) {// 先读取缓存
                scope.data = $rootScope[key];
            } else {
                Page.ajaxPostQuiet("user/tree.do", {deptId: scope.deptId, userId: scope.userId}, function (response) {
                    $rootScope[key] = response.data;// 缓存起来
                    scope.data = $rootScope[key];

                    if (!angular.isUndefined(ngModelController.$viewValue)) {
                        ngModelController.$render();
                    }
                });
            }

            // 初始化树
            scope.onShow = function() {
                if (!scope.orgTree) {
                    var orgTree = $(elem).find('.ztree:eq(0)').attr('id', 'orgTree' + scope.treeId);
                    var posTree = $(elem).find('.ztree:eq(1)').attr('id', 'posTree' + scope.treeId);
                    // 先初始化部门岗位树
                    scope.orgTree = $.fn.zTree.init(orgTree, setting, scope.data.org);
                    // 展开根节点
                    Ztree.expandRoot(scope.orgTree);
                    // 再初始化岗位部门树
                    if (scope.multiple) {
                        scope.posTree = $.fn.zTree.init(posTree, setting, scope.data.pos);
                        // 展开根节点
                        Ztree.expandRoot(scope.posTree);
                    }
                }
                if (scope.needInitTree) {
                    scope.updateTree(scope.orgTree);
                    if (scope.multiple) {
                        scope.updateTree(scope.posTree);
                    }
                }
            }

            // 选择
            scope.updateValue = function() {
                var users = [];
                $(scope.users).each(function(index, user) {
                    users.push(user.id);
                });
                if (scope.multiple) {// 多选
                    ngModelController.$setViewValue(users.join(','));
                } else {
                    ngModelController.$setViewValue(users.length > 0 ? users[0] : '');
                }
                ngModelController.$render(true);
            }

            // 更新tree选中状态
            scope.updateTree = function(ztree) {
                scope.needInitTree = false;
                // 先取消选中
                ztree.setting.view.expandSpeed = "";
                ztree.checkAllNodes(false);
                ztree.expandAll(false);
                ztree.setting.view.expandSpeed = "fast";

                if (!angular.isUndefined(ngModelController.$viewValue) && ngModelController.$viewValue.length > 0) {
                    if (!scope.multiple) {// 单选
                        var node = ztree.getNodeByParam('id', ngModelController.$viewValue, null);
                        ztree.selectNode(node, false);
                        ztree.expandNode(node, true);
                    } else {// 多选
                        $.each(ngModelController.$viewValue.split(','), function (index, id) {
                            var node = ztree.getNodeByParam('id', id, null);
                            if (node && node.type == 'user') {// 叶子节点，这里只选中叶子节点，其关联的节点会相应选中
                                ztree.checkNode(node, true, true);
                            }
                        });
                        // 展开所有选中节点
                        var checkedNodes = ztree.getCheckedNodes(true), checkedLen = checkedNodes.length;
                        if (checkedLen > 0) {
                            for (var i = 0; i < checkedLen; i++) {
                                ztree.expandNode(checkedNodes[i], true);
                            }
                        }
                    }
                }
            }

            ngModelController.$render = function(isUpdateViewOnly) {
                if (!isUpdateViewOnly && !angular.isUndefined(scope.data)) {// 手动赋值
                    //scope.userSelected = [];
                    var tmpArr = (ngModelController.$viewValue || '').replace(/ /g, '').split(',')
                    if (tmpArr.length > 0) {
                        var ids = ',' + tmpArr.join(',') + ',';
                        $(scope.data.org).each(function(index, user) {
                            if (ids.indexOf(',' + user.id + ',') >= 0 && !contains(user)) {
                                //scope.userSelected.push(user);
                                $(tmpArr).each(function(index1, id) {
                                    if (id == user.id) {
                                        tmpArr[index1] = user;// 保持顺序
                                    }
                                });
                            }
                        });
                    }
                    scope.userSelected = tmpArr;

                    scope.users = angular.copy(scope.userSelected);
                    scope.needInitTree = true;
                }
                if (scope.users.length == 0) {// 没有选中的
                    input.val('');
                } else {
                    var names = [];
                    $(scope.users).each(function(index, user) {
                        names.push(user.name);
                    });
                    input.val(names.join(', '));
                }
            }

            function getChildren(treeNode){
                var arr = [];
                arr.push(treeNode);
                if (treeNode.isParent){
                    for(var obj in treeNode.children){
                        arr = arr.concat(getChildren(treeNode.children[obj]));
                    }
                }
                return arr;
            }

            function contains(user) {
                var flag = false;
                $(scope.userSelected).each(function (index, user1) {
                    if (user1.id == user.id) {
                        flag = true;
                        return false;
                    }
                });
                return flag;
            }
        }
    };
}]);